﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.IO;

namespace SMSSendReceiveTool
{
    public partial class Form1 : Form
    {
        public delegate void DelegateRead();
        DelegateRead delegatRead;
        private StringBuilder _readedText = new StringBuilder();
       
        bool _tag = false;


        private string sendSMS = string.Empty;//私有字段
        //public Clipboard _clipboard = new Clipboard();

        public Form1()
        {
            InitializeComponent();
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;
            foreach (string s in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(s);
            }
            comboBox2.Items.Add("9600");
            comboBox2.Items.Add("19200");
            comboBox2.Items.Add("38400");
            comboBox2.Items.Add("57600");
            comboBox2.Items.Add("115200");

            //  初始化年会相关数据
            MeetingPrepare();
        }
        public bool gettag
        {
            get { return _tag; }
            set { this._tag = value; }
        }
        public string SendMessage//get 和set私有字段
        {
            get { return sendSMS; }
            set { this.sendSMS = value; }
        }

        public SerialPort SerialPort
        {
            get { return ss_port; }
            //set { this._serailport = value; }
        }
        public ListView ListViewSend
        {
            get { return listView1; }
           // set{}
        }
        public ListView listviewreceive
        {
            get { return listView2; }
        }
        /*public List<string> huifu
        {
            get { return zhuangtai; }
        }*/
        public StringBuilder sb
        {
            get { return _readedText; }
        }

        

        private void button1_Click_1(object sender, EventArgs e)
        {
            sendmsg.ReturnInstance(this, string.Empty).Show();
            
        }

        private void button5_Click_1(object sender, EventArgs e)//连接端口
        {
            try
            {
                if (comboBox1.Text == string.Empty && comboBox2.Text == string.Empty)
                { MessageBox.Show("请输入端口号和波特率"); return; }
                if (ss_port.IsOpen)
                {
                    ss_port.Close();

                }
                ss_port.PortName = comboBox1.Text;
                ss_port.BaudRate = Int32.Parse(comboBox2.Text);
                ss_port.Open();
                delegatRead = ReadReceivedDate;
                //打开端口后的初始化设置
                ss_port.Write("AT+CMGF=0\r");//编码格式为PDU
                ss_port.Write("AT+CNMI=2,2\r");//收到新消息后直接通知TE，不存在卡上
                
                textBox3.Text = "连接成功";
                //MessageBox.Show("ok");//调试
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                button4.Enabled = true;
                comboBox1.Enabled = false;
                comboBox2.Enabled = false;
                textBox3.Enabled = false;



            }
            catch (Exception eee)
            {
                MessageBox.Show("错误：" + eee.Message);

            }
        }

        private void ReadReceivedDate()
        {
            int len = ss_port.BytesToRead;
            Byte[] output = new Byte[len];
            ss_port.Read(output, 0, len);
            _readedText.Append(System.Text.Encoding.ASCII.GetString(output));

            if (_readedText.ToString().Contains("+CMT"))       //+CMT表示收到短信提示的AT命令
            {
                PDUencoding pducode = new PDUencoding();

                // listView2.Items.Clear();

                string ss = _readedText.ToString();

                while (ss.Contains("+CMT"))
                {
                    int kaish = ss.IndexOf("+CMT");

                    ss = ss.Substring(kaish);
                    int begin = ss.IndexOf("0891");
                    if (begin == -1) break;
                    string temp = ss.Substring(begin);

                    int end = temp.IndexOf("\r\n");
                    
                    //int length = end - temp;
                    string temp1 = temp.Substring(0, end);
                    string num_and_contend = pducode.DecodingSMS(temp1);
                    int fengefu = num_and_contend.IndexOf("@@");
                    string num = num_and_contend.Substring(0, fengefu);
                    //string contend = num_and_contend.Substring(fengefu + 2);
                    num_and_contend = num_and_contend.Substring(fengefu + 2);
                    int fenggefu2 = num_and_contend.IndexOf("@@");
                    string time = num_and_contend.Substring(0, fenggefu2);
                    string contend = num_and_contend.Substring(fenggefu2 + 2);
                    
                    //  进入年会相关流程处理
                    MeetingProcess(num, contend, time);
                    
                    ListViewItem li = new ListViewItem();
                    li.SubItems.Clear();
                    li.SubItems[0].Text = time;
                    li.SubItems.Add(num);
                    li.SubItems.Add(contend);
                    
                    li.SubItems.Add("未回复");
                    
                    listView2.Items.Add(li);
                    listView2.Items[listView2.Items.Count - 1].UseItemStyleForSubItems = false;
                    listView2.Items[listView2.Items.Count - 1].SubItems[3].ForeColor = Color.Red;
                    listView2.Items[listView2.Items.Count - 1].EnsureVisible();
                    _readedText.Remove(_readedText.ToString().IndexOf("+CMT"), begin+end);

                    ss = temp.Remove(0, end);
                }
                /*for (int i = 0; i < zhuangtai.Count; i++)
                {
                    listView2.Items[i].SubItems[3].Text = zhuangtai[i];
                }*/
            }
        }

        private void ss_port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                //Trace.WriteLine(e.EventType.ToString());
                this.Invoke(delegatRead);
                //excuteATcommand();
            }
            catch (Exception ex)
            {
                //Trace.WriteLine(ex.Message);
                //MessageBox.Show(ex.Message);
            }
        }

        private void listView2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (listView2.SelectedItems.Count != 0)
            {
                if (listView2.SelectedItems[0].Checked == false)
                    listView2.SelectedItems[0].Checked = true;
                else listView2.SelectedItems[0].Checked = false;

                ListViewItem item1 = listView2.SelectedItems[0];
                string num = item1.SubItems[1].Text;
                _tag = true;
                sendmsg.ReturnInstance(this, num).Show();
            }
            /*item1.SubItems[3].Text = "已回复";
            zhuangtai.Clear();
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                zhuangtai.Add(listView2.Items[i].SubItems[3].Text);
            }*/
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
            if (listView1.SelectedItems.Count!=0)
            {
                if (listView1.SelectedItems[0].Checked == false)
                    listView1.SelectedItems[0].Checked = true;
                else listView1.SelectedItems[0].Checked = false;
                
                ListViewItem item1 = listView1.SelectedItems[0];
                string num = item1.SubItems[1].Text;

                sendmsg.ReturnInstance(this, num).Show();
            }
            
        }

        private void button3_Click(object sender, EventArgs e)//清空消息
        {

           DialogResult result = MessageBox.Show("你确定要删除所有消息?", "删除消息", MessageBoxButtons.YesNo);
           if (result == DialogResult.Yes)
           {
               listView1.Items.Clear();
               listView2.Items.Clear();
               _readedText.Remove(0, _readedText.Length);
           }

        }

        private void button2_Click(object sender, EventArgs e)//保存消息
        {
            /*try
            {

                StreamWriter sw = new StreamWriter(dir_send, true);
                sw.WriteLine(DateTime.Now.ToLongDateString() + DateTime.Now.ToShortTimeString() + ":");
                for (int i = 0; i < listView1.Items.Count; i++)
                {
                    sw.WriteLine("发送的短信" + (i + 1) + "\r\n" + "发送时间：" + listView1.Items[i].SubItems[0].Text + " 发送方号码：  " + listView1.Items[i].SubItems[1].Text + " 短信内容：  " + listView1.Items[i].SubItems[2].Text);

                }
                sw.WriteLine();
                sw.WriteLine();
                sw.Close();

                StreamWriter sw_receive = new StreamWriter(dir_receive, true);
                sw_receive.WriteLine(DateTime.Now.ToLongDateString() + DateTime.Now.ToShortTimeString() + ":");
                for (int i = 0; i < listView2.Items.Count; i++)
                {
                    sw_receive.WriteLine("收到的短信" + (i + 1) + "\r\n" + "接收时间：" + listView2.Items[i].SubItems[0].Text + " 对方号码：  " + listView2.Items[i].SubItems[1].Text + " 短信内容：  " + listView2.Items[i].SubItems[2].Text);

                }
                sw_receive.WriteLine();
                sw_receive.WriteLine();
                sw_receive.Close();
                MessageBox.Show("保存成功！");
            }
            catch (Exception exed)
            {
                MessageBox.Show(exed.Message);
                
            }*/
            //使用saveasdialog重写
            //context为要写的文件内容
            string context=string.Empty;
            context += "保存时间：";
            context += DateTime.Now.ToLongDateString() + DateTime.Now.ToShortTimeString() + ":\r\n";
            context += "发送的短信：\r\n";
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if (listView1.Items[i].Checked == true)
                context += (i + 1) + "\r\n" + "发送时间：" + listView1.Items[i].SubItems[0].Text + " 发送方号码：  " + listView1.Items[i].SubItems[1].Text + " 短信内容：  " + listView1.Items[i].SubItems[2].Text+"\r\n";

            }
            context += "\r\n\r\n收到的短信：\r\n";
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                if (listView2.Items[i].Checked == true)
                context +=(i + 1) + "\r\n" + "接收时间：" + listView2.Items[i].SubItems[0].Text + " 对方号码：  " + listView2.Items[i].SubItems[1].Text + " 短信内容：  " + listView2.Items[i].SubItems[2].Text+"\r\n";

            }

            if(saveFileDialog1.ShowDialog()==DialogResult.OK)
                File.WriteAllText(saveFileDialog1.FileName, context);

        }

        private void button4_Click(object sender, EventArgs e)
        {
            ATCommandTest.ReturnInstance(this).Show();
        }

        private void listView2_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            
            if (this.listView2.Columns[e.Column].Tag == null)
                this.listView2.Columns[e.Column].Tag = true;
            bool tabK = (bool)this.listView2.Columns[e.Column].Tag;
            if (tabK)
                this.listView2.Columns[e.Column].Tag = false;
            else
                this.listView2.Columns[e.Column].Tag = true;
            this.listView2.ListViewItemSorter = new ListViewSort(e.Column, this.listView2.Columns[e.Column].Tag);
            this.listView2.Sort();
        }

        private void listView2_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
        {
            string context = e.Item.SubItems[2].Text;
            toolTip1.SetToolTip(listView2, context);
        }

        private void listView1_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
        {
            string context = e.Item.SubItems[2].Text;
            toolTip1.SetToolTip(listView1, context);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                if (listView2.Items[i].Checked == true)
                    listView2.Items[i].Remove();
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                listView2.Items[i].Checked = true;
                  
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                listView1.Items[i].Checked = true;

            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if (listView1.Items[i].Checked == true)
                    listView1.Items[i].Remove();
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                listView1.Items[i].Checked = false;

            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                listView2.Items[i].Checked = false;

            }
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView2.SelectedItems.Count != 0)
            {
                string contest = listView2.SelectedItems[0].SubItems[2].Text;
                Clipboard.SetText(contest);
            }
        }
    }


    class ListViewSort : IComparer
    {
        private int col;
        private bool descK;

        public ListViewSort()
        {
            col = 0;
        }
        public ListViewSort(int column, object Desc)
        {
            descK = (bool)Desc;
            col = column; //当前列,0,1,2...,参数由ListView控件的ColumnClick事件传递
        }
        public int Compare(object x, object y)
        {
            int tempInt = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
            if (descK) return -tempInt;
            else return tempInt;
        }
    }
}